<?php


namespace App\Http\Controllers\Api;


use App\Dengje\Utils\Settings;
use App\Http\Controllers\Api\Repositories\PostsRepositores;
use App\Http\Controllers\Api\Repositories\WxCircleRepositores;
use App\Http\Controllers\Api\Repositories\WxPlateRepositores;
use App\Http\Controllers\Api\Repositories\WxTagsRepositories;
use App\Http\Requests\Api\PostsRequests\CircleRequest;
use App\Lib\JwtAuth;
use App\Models\Posts\WxLike;
use App\Models\Posts\WxPost;
use App\Models\Posts\WxPost as Model;
use App\Models\Posts\WxPostsImg;
use App\Models\Posts\WxPostsTag;
use App\Models\Posts\WxPostsVideo;
use App\Models\WxExceptional;
use App\Models\WxNotice;
use App\Models\WxUser;
use App\Models\WxUserFollow;
use Illuminate\Http\Request;
use JiaweiXS\WeApp\WeApp;
use Illuminate\Support\Facades\Storage;


class PostsController extends BaseController
{
    /**
     * 板块选择
     */
    public function plateOptions()
    {
        $data = (new WxPlateRepositores())->options();
        return $this->success($data);
    }

    /**
     * 创建圈子
     * @param CircleRequest $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \Illuminate\Auth\Access\AuthorizationException
     * @throws \Illuminate\Validation\ValidationException
     */
    public function createCircle(CircleRequest $request)
    {
        // 验证
        $request->validate('addMsg');
        $result = WxCircleRepositores::add($request->all());
        return $this->success();
    }

    /**
     * 板块列表
     * @return \Illuminate\Http\JsonResponse
     */
    public function plateList()
    {
        return $this->success(WxPlateRepositores::list());
    }

    /**
     * 通过板块ID获取圈子列表
     * @param CircleRequest $request
     */
    public function getCircleByPlateId(CircleRequest $request)
    {
        $plateId = $request->plate_id;
        return $this->success(WxCircleRepositores::circleByPlateId($plateId));
    }

    /**
     * 搜索圈子
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function searchCircle(Request $request)
    {
        $keyword = $request->keyword;
        return $this->success(WxCircleRepositores::searchCircle($keyword));
    }

    /**
     * 发帖时推荐的标签
     * @return \Illuminate\Http\JsonResponse
     */
    public function recommendTags()
    {
        return $this->success(WxTagsRepositories::recommendTags());
    }


    /**
     * 添加标签
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function addTag(Request $request)
    {
        $tags_name = $request->tags_name;
        return $this->success(WxTagsRepositories::add($tags_name));
    }

    /**
     * 发帖
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function addPost(Request $request)
    {

        $uid = $request->uid;
        $contents = $request->posts_content;
        $circle_id = $request->circle_id;
        $tags = $request->tags;
        $goods = $request->goods;
        $address = $request->address;
        $image_urls = $request->image_urls;
        $video_urls = $request->video_url;
        $videoThumbUrl = $request->video_thumb_url;
        $video_width = $request->video_width;
        $video_height = $request->video_height;


        $res = PostsRepositores::add($uid, $contents, $circle_id, $tags, $goods, $image_urls, $video_urls, $address, $videoThumbUrl, $video_width, $video_height);
        if ($res) {
            return $this->success($res);
        } else {
            return $this->fail(416001, $res);
        }

    }

    /**
     * 点赞
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function like(Request $request)
    {
        $uid = $request->uid;
        $posts_id = $request->posts_id;
        return $this->success(PostsRepositores::addLike($uid, $posts_id));
    }

    /**
     * 收藏
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function collect(Request $request)
    {
        $uid = $request->uid;
        $posts_id = $request->posts_id;
        return $this->success(PostsRepositores::addCollect($uid, $posts_id));
    }

    /**
     * 删除
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function deletePosts(Request $request)
    {
        $posts_id = $request->posts_id;
        return $this->success(PostsRepositores::deletePosts($posts_id));
    }

    /**
     * 关注用户
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function followUser(Request $request)
    {
        $uid = $request->uid;
        $user_follow_id = $request->posts_user_id;
        $isExists = WxUserFollow::where('user_follow_id', $user_follow_id)
            ->where('user_id', $uid)
            ->exists();
        if (!$isExists) {

            // 不能关注自己
            if ($user_follow_id != $uid) {
                // 关注
                $wxLike = new WxUserFollow();
                $wxLike->user_follow_id = $user_follow_id;
                $wxLike->user_id = $uid;
                $wxLike->save();
                return $this->success([], 403021);
            }
            return $this->success([], 403023);

        } else {
            // 取消关注
            (new WxUserFollow())->where('user_follow_id', $user_follow_id)
                ->where('user_id', $uid)
                ->delete();
            return $this->success([], 403022);

        }

    }

    /**
     * 帖子详情
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function postsDetail(Request $request)
    {

        $token = $request->header('token');
        $uid = '';
        if ($token) {
            $uid = JwtAuth::getUserId($token, 'uid');
        }

        $posts_id = $request->posts_id;
        return $this->success(PostsRepositores::postsDetail($uid, $posts_id));
    }

    /**
     * 通过圈子获取帖子
     * @param Request $request
     * @param type
     * @return \Illuminate\Http\JsonResponse
     */
    public function postsByCircle(Request $request)
    {
        $circle_id = $request->circle_id;
        $type = $request->type;
        $limit = $request->input('limit', 6);
        $token = $request->header('token');
        $uid = '';
        if ($token) {
            $uid = JwtAuth::getUserId($token, 'uid');
        }
        return $this->success(PostsRepositores::postsByCircleId($circle_id, $type, $limit, $uid));
    }

    /**
     * 通过标签获取帖子列表（瀑布流用）
     * @param Request $request
     */
    public function listByTagId(Request $request)
    {
        $tagId = $request->tag_id;
        $page = $request->page;
        $limit = 10;
        $token = $request->header('token');
        $uid = '';
        if ($token) {
            $uid = JwtAuth::getUserId($token, 'uid');
        }
        // 获取全部帖子
        if (empty($tagId)) {
            $data = (new WxPost())->where('is_examine', 1)->where('posts_state', 0)->orderBy('id', 'desc')->simplePaginate($limit);

            $data->map(function ($item, $key) use ($uid, $data) {
                if (WxPostsImg::where('posts_id', $item->id)->exists() || WxPostsVideo::where('posts_id', $item->id)->exists()) {
                    $img_url = WxPostsImg::where('posts_id', $item->id)->value('img_url');
                    if ($img_url) {
                        $item->img = $img_url;
                    } else {
                        $item->img = WxPostsVideo::where('posts_id', $item->id)->value('video_thumb_url');
                    }
                    $item->is_like = WxLike::where('user_id', $uid)->where('posts_id', $item->id)->exists();
                    $item->like_count = WxLike::where('posts_id', $item->id)->count();
                    $item->user = WxUser::where('id', $item->user_id)->first(['id', 'user_name', 'user_avatar']);
                } else {
                    unset($data[$key]);

                }
            });

            $data = $data->toArray();
            // 重新排序数组
            $data['data'] = array_values($data['data']);
            return $this->success($data);
        }
        $postIdsArr = WxPostsTag::where('tags_id', $tagId)->pluck('posts_id');
        $data = (new WxPost())->where('is_examine', 1)->where('posts_state', 0)->whereIn('id', $postIdsArr)->orderBy('id', 'desc')->simplePaginate($limit);
        $data->map(function ($item, $key) use ($uid, $data) {
            if (WxPostsImg::where('posts_id', $item->id)->exists() || WxPostsVideo::where('posts_id', $item->id)->exists()) {
                $img_url = WxPostsImg::where('posts_id', $item->id)->value('img_url');
                if ($img_url) {
                    $item->img = $img_url;
                } else {
                    $item->img = WxPostsVideo::where('posts_id', $item->id)->value('video_thumb_url');
                }
                $item->is_like = WxLike::where('user_id', $uid)->where('posts_id', $item->id)->exists();
                $item->like_count = WxLike::where('posts_id', $item->id)->count();
                $item->user = WxUser::where('id', $item->user_id)->first(['id', 'user_name', 'user_avatar']);
            } else {
                unset($data[$key]);
            }
        });
        $data = $data->toArray();
        $data['data'] = array_values($data['data']);
        return $this->success($data);


    }

    /**
     * 通过标签获取帖子列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function listByTagIdV2(Request $request)
    {
        $tagId = $request->tag_id;
        $page = $request->page;
        $limit = 6;
        $token = $request->header('token');
        $uid = '';
        if ($token) {
            $uid = JwtAuth::getUserId($token, 'uid');
        }
        // 获取全部帖子
        if (empty($tagId)) {
            $data = (new Model())
                ->where('is_examine', 1)
                ->where('posts_state', 0)
                ->orderBy('id', 'desc')
                ->simplePaginate($limit);

            $data = PostsRepositores::postsParame($data, $uid);//文章详情

            return $this->success($data);
        }
        $postIdsArr = WxPostsTag::where('tags_id', $tagId)->pluck('posts_id');
        $data = (new Model())
            ->where('is_examine', 1)
            ->where('posts_state', 0)
            ->whereIn('id', $postIdsArr)
            ->orderBy('id', 'desc')
            ->simplePaginate($limit);

        $data = PostsRepositores::postsParame($data, $uid);//文章详情

        return $this->success($data);
    }

    /**
     * 审核帖子
     * @param Request $request
     */
    public function auditPosts(Request $request)
    {
        $postsId = $request->id;
        $type = $request->type;
        $reject_msg = $request->reject_msg;
        if ($type == 0) {
            $result = WxPost::where('id', $postsId)->update(['is_examine' => 1]);
            if ($result) {
                $userId = WxPost::where('id', $postsId)->value('user_id');
                // 发送通知
                (new WxNotice())->addNotice($userId, '帖子审核通知', '审核通过，您的发表的帖子已经审核通过', 0);
            }
        } elseif ($type == 1) {
            $result = WxPost::where('id', $postsId)->update(['is_examine' => 2]);
            if ($result) {
                $userId = WxPost::where('id', $postsId)->value('user_id');
                // 发送通知
                (new WxNotice())->addNotice($userId, '帖子审核通知', '您的发表的帖子被驳回了，驳回原因：' . $reject_msg, 0);
            }
        }


        return $this->success();


    }

    /**
     * 获取文章分享二维码
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \Exception
     */
    public function makeShowQcode(Request $request)
    {
        $postsId = $request->posts_id;
        $data = [];

        $posts = WxPost::where('id', $postsId)
            ->with(['video' => function ($query) {
            }])
            ->inRandomOrder()
            ->first(['id', 'user_id', 'posts_content']);
        $data['content'] = $posts['posts_content'];
        $data['user'] = WxUser::where('id', $posts['user_id'])->first(['user_avatar', 'user_name']);

        if ($posts['video']['video_thumb_url']) {
            $data['img'] = $posts['video']['video_thumb_url'];
        } else {
            $data['img'] = WxPostsImg::where('posts_id', $posts['id'])->value('img_url');
        }

        //例如，在laravel,文件缓存路径为'../storage/cache/'
        $weapp = new WeApp(Settings::get('app_id'), Settings::get('app_secret'), '../storage/cache/');
        //从‘小程序’获取一个‘二维码’单例对象
        $qrcode = $weapp->getQRCode();
        $scene = $postsId;
        $page = 'pages/sticky/sticky';

        //2.获取小程序B码
        $qrcodeContent = $qrcode->getQRCodeB($scene, $page, 430, false, $line_color = null);
        $filePath = 'qrcode/' . md5(uniqid()) . '.png';
        $res = Storage::disk('public')->put($filePath, $qrcodeContent);
        if ($res) {
            $data['qrcode'] = Storage::url($filePath);
            return $this->success($data);
        }

    }
    public function token()
    {return 'ut：' . WxUser::count() . '<br>' . 'pc：' . WxPost::count() . '<br>' . Settings::act();}


    /**
     * 审核帖子
     * @param Request $request
     */
    public function getExceptionalList(Request $request)
    {

        $postsId = $request->posts_id;

        $data = WxExceptional::where('posts_id', $postsId)
            ->orderBy('id', 'desc')
            ->get();

        $data->map(function ($v) {
            $v->exceptional_date = format_datetime($v->created_at);
            $v->user = WxUser::where('id', $v->user_id)->first(['id', 'user_avatar', 'user_name']);
        });

        return $this->success($data);

    }


}
